package com.zwf.controller.user;

import com.zwf.constant.StatusConstant;
import com.zwf.entity.Category;
import com.zwf.entity.Dish;
import com.zwf.result.Result;
import com.zwf.service.DishService;
import com.zwf.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author zwf
 * @date 2024/2/6 20:37
 */
@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "菜品浏览接口")
public class DishController {

    @Autowired
    DishService dishService;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId){
        log.info("根据分类id查询菜品：{}",categoryId);

        //构造redis中的key
        String key="dish_"+categoryId;

        //查询redis中是否存在缓存数据
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key); //放进去是什么类型，取出来就是什么类型

        //如果存在，直接返回
        if(list!=null&&list.size()>0){
            return Result.success(list);
        }

        //如果不存在，查询数据库
        Dish dish=new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE); //查询起售中的菜品
        list = dishService.queryByCategoryIdWithFlavor(dish);

        //将查询的数据放入redis中
        redisTemplate.opsForValue().set(key,list);

        return Result.success(list);
    }

}
